package com.tanhua.server.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.tanhua.common.utils.UserThreadLocal;
import com.tanhua.common.vo.ErrorResult;
import com.tanhua.dubbo.api.*;
import com.tanhua.dubbo.pojo.*;
import com.tanhua.dubbo.vo.PageInfo;
import com.tanhua.server.vo.*;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class IMService {

    @DubboReference(version = "1.0.0")
    private HuanXinApi huanXinApi;

    @DubboReference(version = "1.0.0")
    private UserInfoApi userInfoApi;

    @DubboReference(version = "1.0.0")
    private UsersApi usersApi;


    @DubboReference(version = "1.0.0")
     private QuanZiApi quanZiApi;


    @DubboReference(version = "1.0.0")
    private AnnouncementApi announcementApi;



    public UserInfoVo queryUserInfoByUserName(String userName) {
        //根据环信用户名查询用户id
        HuanXinUser huanXinUser = this.huanXinApi.queryHuanXinUserByUserName(userName);

        //根据用户id查询用户信息
        UserInfo userInfo = this.userInfoApi.queryByUserId(huanXinUser.getUserId());

        //封装UserInfoVo
        UserInfoVo userInfoVo = BeanUtil.toBeanIgnoreError(userInfo, UserInfoVo.class);
        userInfoVo.setGender(userInfo.getSex().name().toLowerCase());
        userInfoVo.setMarriage(StrUtil.equals("已婚", userInfo.getMarriage()) ? 1 : 0);
        return userInfoVo;
    }

    /**
     * 添加联系人
     *
     * @param userId
     * @return
     */
    public Object addContacts(Long userId) {
        //注册好友关系到MongoDB
        String result = this.usersApi.saveUsers(UserThreadLocal.get(), userId);
        if (StrUtil.isNotEmpty(result)) {
            //注册好友关系到环信
            Boolean bool = this.huanXinApi.addUserFriend(UserThreadLocal.get(), userId);
            if (bool) {
                return null;
            }
        }
        return ErrorResult.builder().errCode("500").errMessage("添加好友失败！").build();
    }

    /**
     * 查询联系人列表
     *
     * @param page
     * @param pageSize
     * @param keyword  根据关键字搜索
     * @return
     */
    public PageResult queryContactsList(Integer page, Integer pageSize, String keyword) {
        PageResult pageResult = new PageResult();
        pageResult.setPage(page);
        pageResult.setPagesize(pageSize);

        Long userId = UserThreadLocal.get();
        List<UserInfo> userInfoList;
        if (StrUtil.isEmpty(keyword)) {
            //按顺序查询，按照添加时间倒序排序
            PageInfo<Users> pageInfo = this.usersApi.queryUsersList(userId, page, pageSize);
            if (CollUtil.isEmpty(pageInfo.getRecords())) {
                return pageResult;
            }
            //获取用户信息列表
            userInfoList = this.userInfoApi.queryByUserIdList(CollUtil.getFieldValues(pageInfo.getRecords(), "friendId"));
        } else {
            // 把所有的联系人查询出来，再进行筛选
            List<Users> usersList = this.usersApi.queryAllUsersList(userId);
            if (CollUtil.isEmpty(usersList)) {
                return pageResult;
            }
            List<Object> friendIdList = CollUtil.getFieldValues(usersList, "friendId");
            userInfoList = this.userInfoApi.queryListLikeNickName(friendIdList, keyword);
        }

        List<UsersVo> result = new ArrayList<>();

        //封装UsersVo
        for (UserInfo userInfo : userInfoList) {
            UsersVo usersVo = BeanUtil.toBeanIgnoreError(userInfo, UsersVo.class);
            usersVo.setUserId("HX_" + userInfo.getUserId());
            usersVo.setGender(userInfo.getSex().name().toLowerCase());
            usersVo.setCity(StrUtil.subBefore(userInfo.getCity(), '-', false));
            result.add(usersVo);
        }

        pageResult.setItems(result);
        return pageResult;
    }



    /**
     * 查询消息点赞列表
     *
     * @param page
     * @param pageSize
     * @return
     */
    public PageResult queryLikeCommentList(Integer page, Integer pageSize) {
                //获取本账号id
        Long userId = UserThreadLocal.get();
        PageInfo<Comment> pageInfo = this.quanZiApi.queryLikeCommentListByUser(userId, page, pageSize);
      return this.fillUserCommentList(pageInfo);

    }



    /**
     * 查询消息评论列表
     *
     * @param page
     * @param pageSize
     * @return
     */
    public PageResult queryUserCommentList(Integer page, Integer pageSize) {
        //获取本账号id
        Long userId = UserThreadLocal.get();
        PageInfo<Comment> pageInfo = this.quanZiApi.queryCommentListByUser(userId, page, pageSize);
        return this.fillUserCommentList(pageInfo);


    }


    /**
     * 查询消息喜欢列表
     *
     * @param page
     * @param pageSize
     * @return
     */
    public PageResult queryLoveCommentList(Integer page, Integer pageSize) {
        //获取本账号id
        Long userId = UserThreadLocal.get();
        PageInfo<Comment> pageInfo = this.quanZiApi.queryLoveCommentListByUser(userId, page, pageSize);
        return this.fillUserCommentList(pageInfo);

    }



    //封装方法
    private PageResult fillUserCommentList(PageInfo<Comment> pageInfo){
       PageResult pageResult=new PageResult();
       pageResult.setPage(pageInfo.getPageNum());
       pageResult.setPagesize(pageInfo.getPageSize());
        List<Comment> recordsList = pageInfo.getRecords();
        if(CollUtil.isEmpty(recordsList)){
            //如果没有查到数据
            return pageResult;
        }
        List<Object> userIdList = CollUtil.getFieldValues(recordsList, "userId");
        List<UserInfo> userInfoList = this.userInfoApi.queryByUserIdList(userIdList);
        List<MessageCommentVo> messageCommentVoList = new ArrayList<>();
        //遍历结果集
        for (Comment comment : recordsList){
            //遍历用户信息集
                    for(UserInfo userInfo : userInfoList){
                        //如果结果集和信息集Id相等，则进行封装
                        if(ObjectUtil.equals(comment.getUserId(), userInfo.getUserId())){
                            MessageCommentVo messageCommentVo = new MessageCommentVo();
                            messageCommentVo.setId(comment.getUserId().toString());
                            messageCommentVo.setAvatar(userInfo.getLogo());
                            messageCommentVo.setNickname(userInfo.getNickName());
                            messageCommentVo.setCreateDate(DateUtil.formatDate(new Date(comment.getCreated())));

                            messageCommentVoList.add(messageCommentVo);

                        }
                    }
        }
        pageResult.setItems(messageCommentVoList);

        return pageResult;

    }


    public PageResult queryMessageAnnouncementList(Integer page, Integer pageSize) {
        PageResult pageResult = new PageResult();
        pageResult.setPage(page);
        pageResult.setPagesize(pageSize);
        //调用查询
        IPage<Announcement> announcementIPage = this.announcementApi.queryList(page, pageSize);
        List<Announcement> records = announcementIPage.getRecords();
        //判断
        if(CollUtil.isEmpty(records)){
            return pageResult;
        }
      //不为空进行封装
        List<AnnouncementVo> announcementVoList = new ArrayList<>();
        for(Announcement record:records){
            AnnouncementVo announcementVo = new AnnouncementVo();
            announcementVo.setId(record.getId().toString());
            announcementVo.setTitle(record.getTitle());
            announcementVo.setDescription(record.getDescription());
            announcementVo.setCreateDate(DateUtil.formatDate(record.getCreated()));
            announcementVoList.add(announcementVo);
        }
             pageResult.setItems(announcementVoList);

        return pageResult;

    }

    public void removeUser(Long uid) {
        //删除好友关系
        Long userId = UserThreadLocal.get();
        Boolean result = this.usersApi.removeUsers(userId, uid);
        if(result){
            //将环信平台的好友关系解除
            this.huanXinApi.removeUserFriend(userId, uid);
        }
    }
}
